package com.jb.workflow.app.bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.bean.Entity;
import net.oschina.app.common.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DefinitionList extends Entity {
	
	public final static int CATALOG_RUNNING = 1;//正在运行实例
	public final static int CATALOG_COMPLETE = 2;//历史实例
	public final static int CATALOG_ALL = 3;//全部
	
	private int pageSize;
	private List<ProcessInst> insList = new ArrayList<ProcessInst>();
	
	public List<ProcessInst> getInslist() {
		return insList;
	}
	
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public static InstanceList parse(InputStream inputStream, final int catalog) throws IOException, AppException {
		
		InstanceList list = new InstanceList();
		ProcessInst instance;
		boolean completed = catalog == CATALOG_COMPLETE;
		
		String result = StringUtils.toConvertString(inputStream);
		
		try {
			JSONObject resObj = new JSONObject(result);
			if (resObj != null) {
				JSONArray arr = (JSONArray) resObj.get("data");
				for (int i = 0; i < arr.length(); i++) {
					JSONObject jsObj = (JSONObject) arr.get(i);
					if (jsObj != null) {
						instance = new ProcessInst();
						instance.setId(jsObj.getInt("id"));
						//instance.setCompleted(jsObj.optBoolean("completed"));
						instance.setCompleted(completed);
						instance.setUrl(jsObj.optString("url"));
						instance.setActivityId(jsObj.optString("activityId"));
						instance.setProcessDefinitionId(jsObj.optString("processDefinitionId"));
						instance.setProcessDefinitionUrl(jsObj.optString("processDefinitionUrl"));
						if (!jsObj.isNull("startTime")) {
							String rawDate = jsObj.getString("startTime").replace('T', ' ');
							String[] rawArr = rawDate.split("\\+");//分割时区
							if (rawArr.length >= 1) instance.setStartDate(rawArr[0]);
						}
						if (!jsObj.isNull("endTime")) {
							String rawDate = jsObj.getString("endTime").replace('T', ' ');
							String[] rawArr = rawDate.split("\\+");//分割时区
							if (rawArr.length >= 1) instance.setEndDate(rawArr[0]);
						}
						instance.setStartUserId(jsObj.optString("startUserId"));
						list.getInslist().add(instance);
					}
				}
				list.setPageSize(resObj.optInt("size", list.getInslist().size()));
			}
			
			return list;
			
		} catch (JSONException e) {
			throw AppException.json(e);
		} finally {
			inputStream.close();
		}
		
	}
}
